package pe.com.rimac.portal.common.token.impl;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import org.apache.log4j.Logger;

import pe.com.rimac.portal.common.token.TokenGenerator;

public class TokenGeneratorImpl implements TokenGenerator 
{
	private static final Logger logger = Logger.getLogger(TokenGeneratorImpl.class);
	
	/**
	 * @see pe.com.rimac.portal.common.token.TokenGenerator#generate(java.lang.String)
	 */
	@Override
	public String generate(String idtransaccion, String id, String keyword, String params) 
	{
		String key = getKey(idtransaccion, id, keyword, params);
		return encryptMD5(key);
	}
	
	/**
	 * Obtiene la llave a ser encriptada con el algoritmo MD5. <br/><br/>
	 * La estructura de la llave ser&aacute; la siguiente: <br/><br/>
	 * <strong>IDTRANSACCION + ID + KEYWORD + params</strong>
	 * @param params
	 * @return
	 */
	private String getKey(String idtransaccion, String id, String keyword, String params)
	{
		return idtransaccion + id + keyword + params;
	}
	
	/**
	 * @param key
	 * @return
	 */
	public String encryptMD5(String key)
	{
		key = deleteInvalidCharacters(key);
		StringBuilder token = new StringBuilder("");
		
		try 
		{
			MessageDigest md5 = MessageDigest.getInstance("MD5");
			byte[] input = key.getBytes("CP1252");
			byte[] output = md5.digest(input);
				
			for (int i=0;i<output.length;i++) 
			{
	    		String hex=Integer.toHexString(0xff & output[i]);
	   	     	if(hex.length()==1) token.append('0');
	   	     	token.append(hex);
	    	}
		} 
		catch (NoSuchAlgorithmException e) 
		{
			logger.error("Ocurrio un error al realizar la encriptacion MD5.", e);
		}
		catch (UnsupportedEncodingException e)
		{
			logger.error("Ocurrio un error al realizar la encriptacion MD5.", e);
		}
		
		return token.toString().toUpperCase();
	}
	
	/**
	 * @param key
	 * @return
	 */
	private String deleteInvalidCharacters(String key)
	{
		String newkey = "";
		char invalidChar=(char)13;
		for (int i = 0; i < key.length(); i ++) 
		{
			if (key.charAt(i) != invalidChar) 
			{
				newkey += key.charAt(i);
			}
		}
		return newkey;
	}
}